package com.yds.developtools.utils

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.yds.developtools.utils.YDSBaseHelper.Companion.getContext
import com.yds.utils.entity.AppInfoBean
import java.io.File
import java.util.ArrayList


/**
 * 调用系统的安装界面进行 APK 安装
 * <provider
 *     android:name="androidx.core.content.FileProvider"
 *     android:authorities="${applicationId}.fileprovider"
 *     android:exported="false"
 *     android:grantUriPermissions="true">
 *         <meta-data
 *              android:name="android.support.FILE_PROVIDER_PATHS"
 *              android:resource="@xml/file_paths" />
 * </provider>
 */
object YDSAppHelper {

    /**
     * 查询所有应用信息
     * @param isSystemApplication 是否是系统应用
     */
    @Suppress("DEPRECATION")
    fun queryAllAppInfos(isSystemApplication: Boolean): List<AppInfoBean> {
        val mListSystemAppInfos: MutableList<AppInfoBean> = ArrayList<AppInfoBean>()
        val mListThirdAppInfos: MutableList<AppInfoBean> = ArrayList<AppInfoBean>()
        val packageManager = getContext().packageManager
        // 获取到所有安装了的应用程序的信息，包括那些卸载了的，但没有清除数据的应用程序
        val installedApplications =
            packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES)
        for (installedApplication in installedApplications) {
            val appInfo = AppInfoBean()
            appInfo.name = installedApplication.loadLabel(packageManager).toString()
            appInfo.icon = installedApplication.loadIcon(packageManager)
            appInfo.packageName = installedApplication.packageName
            if (installedApplication.flags and ApplicationInfo.FLAG_SYSTEM <= 0) {
                // 三方应用
                mListThirdAppInfos.add(appInfo)
            } else {
                // 系统应用
                mListSystemAppInfos.add(appInfo)
            }
        }
        return if (isSystemApplication) mListSystemAppInfos else mListThirdAppInfos
    }

    /**
     * 判断该包名的应用是否安装
     * @param packageName 应用包名
     */
    @Suppress("unused")
    fun checkAppExist(packageName: String): Boolean {
        try {
            val packageManager = getContext().packageManager
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                packageManager.getApplicationInfo(
                    packageName,
                    PackageManager.MATCH_UNINSTALLED_PACKAGES
                )
            } else {
                packageManager.getApplicationInfo(packageName, 0)
            }
            return true
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return false
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param apkFile 待安装的apk文件
     */
    fun installApp(context: Context, apkFile: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val contentUri = FileProvider.getUriForFile(context, context.packageName + ".fileprovider", apkFile)
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }

    /**
     * 根据包名打开应用
     * @param context 上下文对象
     * @param packageName 要打开的应用的包名
     */
    fun openAppByPackageName(context: Context, packageName: String?) {
        // 获取 PackageManager 实例
        val packageManager = context.packageManager
        try {
            // 获取对应包名应用的启动 Intent
            val launchIntent = packageManager.getLaunchIntentForPackage(packageName!!)
            if (launchIntent != null) {
                // 启动该应用
                context.startActivity(launchIntent)
            } else {
                // 如果获取的 Intent 为空，提示用户应用未安装
            }
        } catch (e: Exception) {
            // 捕获异常并提示用户打开应用失败
            e.printStackTrace()
        }
    }

    /**
     * 卸载app
     * @param packageName 应用包名
     */
    fun uninstallApp(packageName: String): Boolean {
        if (checkAppExist(packageName)) {
            val packageURI = Uri.parse("package:$packageName")
            val intent = Intent(Intent.ACTION_DELETE)
            intent.data = packageURI
            getContext().startActivity(intent)
            return true
        }
        return false
    }
}
